import 'dart:convert';

import 'package:mziot/app/config/api.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/data/profile_entity.dart';
import 'package:mziot/app/data/public_model.dart';
import 'package:mziot/app/data/user_entity.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/public_provider.dart';

class MineProvider {
  //获取验证码
  Future<BaseModel<dynamic>> takeCode(String email, int isLogin) {
    return PublicProvider.request<dynamic>(
        path: Api.takeCode, params: {'email': email, 'isLogin': isLogin});
  }

  //验证码登录
  Future<BaseModel<T>> loginNormal<T>(String email, String? code, String? password) {
    var params = {'email': email};
    if (code != null && code.isNotEmpty) {
      params['otpCode'] = code;
      params['loginMethod'] = '2';
    }
    if (password != null && password.isNotEmpty) {
      params['password'] = password;
      params['loginMethod'] = '1';
    }
    return PublicProvider.request<T>(path: Api.loginEmail, params: params);
  }

  //注册
  Future<BaseModel<T?>> register<T>(
    String email,
    String password,
    String code, {
    String? name,
    String? avatar,
  }) {
    var params = {'email': email, 'firstPassword': password, 'emailOtpCode': code};
    if (name != null) {
      params['nickname'] = name;
    }
    if (avatar != null) {
      params['headimg'] = avatar;
    }
    return PublicProvider.request<T>(path: Api.register, params: params);
  }

  //个人信息
  Future<BaseModel<ProfileEntity>> takeMineInfo() {
    return PublicProvider.request<ProfileEntity>(path: Api.mineInfo).then((value) async {
      if (value.isSuccess) {
        GlobalConst.userModel?.nickName = value.data?.nickName ?? value.data?.userName;
        GlobalConst.userModel?.userHeadImg = value.data?.userHeadImg;
        String info = json.encode(GlobalConst.userModel!.toJson());
        await GlobalConst.sharedPreferences?.setString(Constant.kUser, info);
      }
      return value;
    });
  }

  //三方登录
  Future<BaseModel<UserEntity>> unionLogin(String uid, int type, String? name, String token) {
    var params = {};
    params['uid'] = uid;
    params['type'] = type;
    params['userName'] = name;
    params['accessToken'] = token;
    return PublicProvider.request<UserEntity>(path: Api.unionLogin, params: params);
  }

  //绑定邮箱
  Future<BaseModel<UserEntity>> bindEmail(String email, String code) {
    var params = {};
    params['email'] = email;
    params['emailOtp'] = code;
    return PublicProvider.request<UserEntity>(path: Api.bindEmail, params: params);
  }
}
